package com.link510.aitools.services;


import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.Utils;
import com.link510.aitools.R;
import com.link510.aitools.core.errors.SateCollect;
import com.link510.aitools.core.listen.CWMListener;
import com.link510.aitools.core.message.MessageInfo;
import com.link510.aitools.data.AirobotDtata;
import com.orhanobut.logger.Logger;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;

import io.reactivex.schedulers.Schedulers;

public class QiniuUtils extends BaseService {

    private final String accesskey;
    private final String secretkey;
    private final String bucket;

    private UploadManager uploadManager = null;


    Configuration cfg = null;

    private static QiniuUtils mInstance = null;

    public static QiniuUtils getInstance() {

        if (mInstance == null) {
            synchronized (QiniuUtils.class) {
                if (mInstance != null) {
                    return mInstance;
                }
                mInstance = new QiniuUtils();
            }
        }

        return mInstance;
    }

    private QiniuUtils() {

        this.bucket = Utils.getApp().getString(R.string.qiniu_bucket);
        this.accesskey = Utils.getApp().getString(R.string.qiniu_accesskey);
        this.secretkey = Utils.getApp().getString(R.string.qiniu_secretkey);

        Configuration cfg = new Configuration.Builder()
                .connectTimeout(10)              // 链接超时。默认90秒
                .useHttps(true)                  // 是否使用https上传域名
                .responseTimeout(60)             // 服务器响应超时。默认90秒
                .zone(FixedZone.zone0)           // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(cfg);
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return
     */
    public void upload(File file, CWMListener<String> listener2) {

        try {

            if (!file.exists()) {
                if (listener2 != null) {
                    onErrorAction(listener2, -1, "文件上传失败");
                }
                return;
            }

            getUploadToken("airobot2", new CWMListener<MessageInfo<String>>() {
                @Override
                public void onSuccess(String message, MessageInfo<String> messageInfo) {

                    if (!messageInfo.getState().equals(0)) {
                        return;
                    }

                    String token = messageInfo.getContent();

                    String fileName = file.getName();

                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    String key = ApplicationUtils.getInstance().getApplication().getDeviceSN() +
                            "/" + System.currentTimeMillis() + "temp." + suffix;

                    QiniuUtils.this.uploadManager.put(file, key, token, new UpCompletionHandler() {

                        /**
                         * 用户自定义的内容上传完成后处理动作必须实现的方法
                         * 建议用户自己处理异常。若未处理，抛出的异常被直接丢弃。
                         *
                         * @param key      文件上传保存名称
                         * @param info     上传完成返回日志信息
                         * @param response 上传完成的回复内容
                         */
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {


                            if (!info.isOK()) {
                                onErrorAction(listener2, -4, "文件上传失败");
                                return;
                            }

                            Logger.e("文件上传成功:" + JSON.toJSONString(key));
                            onSuccessAction(listener2, "文件上传成功", "http://" + Utils.getApp().getString(R.string.qiniu_url) + "/" + key);
                        }
                    }, null);

                }

                @Override
                public void onError(int code, String message) {
                    onErrorAction(listener2, -3, "数据消息解析异常");
                }
            });


        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }


    /**
     * 获取图片
     *
     * @param bucket 空间
     * @return Observable<MessageInfo < QiniuFileListingModel>>
     */
    public void getUploadToken(String bucket, CWMListener<MessageInfo<String>> listener) {

        try {

            AirobotDtata.getInstance().getUploadToken(bucket).subscribeOn(Schedulers.newThread())
                    .subscribe(messageInfo -> {

                        if (messageInfo == null) {
                            onErrorAction(listener, -3, "数据消息解析异常");
                            return;
                        }

                        if (!SateCollect.SUCCESS.equals(messageInfo.getState())) {
                            onErrorAction(listener, messageInfo.getState(), messageInfo.getMessage());
                            return;
                        }

                        onSuccessAction(listener, messageInfo.getMessage(), messageInfo);

                    }, t -> {
                        // 处理异常

                        try {
                            onErrorAction(listener, -2, "发送命令发生异常");
                            Logger.e(t, "发送命令发生异常");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    });

        } catch (Exception ex) {
            Logger.e(ex, "发送命令发生异常");
            onErrorAction(listener, -1, "发送命令发生异常");
        }
    }

}
